package com.intretech.umsin.pay.component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.intretech.umsin.pay.config.AlipayProperties;
import com.intretech.umsin.pay.vo.AlipayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @version V1.0
 * @ClassName: AlipayTemplate
 * @Description: 功能描述
 * @author: 李启联
 * @date: 2022-8-12 9:13
 * @Copyright: Copyright (c) 2022
 */
@Component
@Slf4j
public class AlipayTemplate {

    @Autowired
    private AlipayProperties properties;

    public  String pay(AlipayVo vo) throws AlipayApiException {

        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(properties.getGatewayUrl(),
                properties.getApp_id(),properties.getMerchant_private_key(), "json",
                properties.getCharset(),properties.getAlipay_public_key(), properties.getSign_type());

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(properties.getReturn_url());
        alipayRequest.setNotifyUrl(properties.getNotify_url());

        alipayRequest.setBizContent(vo.toString());

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        log.info("支付宝的响应："+result);

        return result;

    }

    /**
     * 验证签名
     * @param params
     * @return
     * @throws AlipayApiException
     */
    public boolean signVerified(Map params) throws AlipayApiException {
        return AlipaySignature.rsaCheckV1(params,
                properties.getAlipay_public_key(),
                properties.getCharset(),
                properties.getSign_type()); //调用SDK验证签名
    }

}